<template>
  <div>
    <!-- 面包屑区域 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item> 商品管理</el-breadcrumb-item>
      <el-breadcrumb-item>商品分类</el-breadcrumb-item>
    </el-breadcrumb>
    <!-- 卡片区域 -->
    <el-card>
      <!-- 添加分类 -->
      <el-button
        type="primary"
        class="add_Classify"
        @click="addClassifyCascader"
        >添加分类</el-button
      >
      <!-- 表格部分 -->
      <!-- <el-table
        :data="classifylist"
        border
        style="width: 100%"
        :header-cell-style="tableHeaderColor"
      >
        <el-table-column type="index" label="#"></el-table-column>
        <el-table-column prop="cat_name" label="分类名称">
          <tree-table
            :data="classifylist"
            :columns="columns"
            border
            :show-row-hover="false"
            :type-tree="true"
            :selection-type="false"
            :expand-type="false"
          >

          </tree-table>
        </el-table-column>
        <el-table-column label="是否有效"> </el-table-column>
        <el-table-column prop="cat_level" label="排序"> </el-table-column>
        <el-table-column label="操作">
          <el-button size="mini" type="primary" icon="el-icon-edit"
            >编辑</el-button
          >
          <el-button size="mini" type="danger" icon="el-icon-delete"
            >删除</el-button
          >
        </el-table-column>
      </el-table> -->
      <!-- 树形表格 -->
      <tree-table
        :data="classifylist"
        :columns="columns"
        border
        :show-row-hover="false"
        :type-tree="true"
        :selection-type="false"
        :expand-type="false"
        show-index
        index-text="#"
      >
        <!-- 判断是否有效 -->
        <template slot-scope="scope" slot="isOk">
          <i
            class="el-icon-success"
            style="color: lightgreen"
            v-if="scope.row.cat_deleted === false"
          ></i>
          <i class="el-icon-error" style="color: red" v-else></i>
        </template>
        <!-- 排序 -->
        <template slot-scope="scope" slot="sort">
          <el-tag v-if="scope.row.cat_level == 0">一级</el-tag>
          <el-tag type="success" v-else-if="scope.row.cat_level == 1"
            >二级</el-tag
          >
          <el-tag type="danger" v-else>三级</el-tag>
        </template>
        <!-- 操作 -->
        <template slot="opt" slot-scope="scope">
          <!-- <pre>{{ scope.row.cat_id }}</pre> -->
          <el-button
            type="primary"
            icon="el-icon-edit"
            size="mini"
            @click="showEditForm(scope.row)"
            >编辑</el-button
          >
          <el-button
            type="danger"
            icon="el-icon-delete"
            size="mini"
            @click="deleteEditForm(scope.row.cat_id)"
            >删除</el-button
          >
        </template>
      </tree-table>
      <!-- 分页部分 -->
      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="this.classifyinfo.pagenum"
        :page-sizes="[3, 5, 10, 15]"
        :page-size="this.classifyinfo.pagesize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
      >
      </el-pagination>
    </el-card>
    <!-- 添加分类对话框 -->
    <el-dialog
      title="添加分类"
      :visible.sync="addClassifyVisible"
      width="45%"
      @close="resetAddClassify"
      :close-on-click-modal="false"
    >
      <el-form
        :model="addClassify"
        label-width="85px"
        :rules="addClassifyRule"
        ref="addClassifyRef"
      >
        <el-form-item label="分类名称:" prop="cat_name">
          <el-input
            v-model="addClassify.cat_name"
            autocomplete="off"
          ></el-input>
        </el-form-item>
        <el-form-item label="父级分类:">
          <!-- 级联选择器 -->
          <el-cascader
            popper-class="thender"
            v-model="selectKeys"
            :options="addcascaderlist"
            clearable
            :props="addclassifyParams"
            ref="cascaderAddr"
            @change="selectKeysChange"
          ></el-cascader>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="submitAddClassify">提交</el-button>
        <el-button type="primary" @click="resetAddClassify">重置</el-button>
      </div>
    </el-dialog>
    <!-- 编辑分类对话框 -->
    <el-dialog
      title="编辑分类"
      :visible.sync="editClassifyVisible"
      width="45%"
      :close-on-click-modal="false"
    >
      <el-form label-width="80px" :model="editClassify" ref="editClassifyRef">
        <!-- 分类名称 -->
        <el-form-item label="分类名称:">
          <el-input v-model="editClassify.cat_name"></el-input>
        </el-form-item>
        <!-- 分类父级=>级联选择器 -->
        <el-form-item label="分类父级:">
          <el-cascader
            v-model="editSelectKeys"
            :options="editcascaderlist"
            :props="editCascaderProps"
            @change="editSelectKeysChange"
            clearable
            ref="cascaderEditr"
            
          ></el-cascader>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary"  @click="submitEditClassify">提交</el-button>
        <el-button @click="editClassifyVisible=false">取消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import axios from "axios";
export default {
  data() {
    return {
      // 所有的分类列表
      classifylist: [],
      // 获取分类传递参数
      classifyinfo: {
        type: 3,
        pagenum: 1,
        pagesize: 5,
      },
      total: 0,
      //columns(设置表格中列配置信息)
      columns: [
        {
          label: "分类名称",
          prop: "cat_name",
        },
        {
          label: "是否有效",
          type: "template",
          template: "isOk",
        },
        {
          label: "排序",
          type: "template",
          template: "sort",
        },
        {
          label: "操作",
          type: "template",
          template: "opt",
        },
      ],
      // 控制添加分类对话框
      addClassifyVisible: false,
      // 添加分类的对象
      addClassify: {
        cat_name: "",
        cat_level: 0,
        cat_pid: 0,
      },
      // 当前选择级联选择器的值
      selectKeys: [],
      // 添加分类的规则校验
      addClassifyRule: {
        cat_name: [
          { required: "true", message: "请输入分类名称", trigger: "blur" },
        ],
      },
      // 添加分类的选择器选项值
      addcascaderlist: [],
      //地域信息配置参数
      addclassifyParams: {
        label: "cat_name",
        value: "cat_id",
        expandTrigger: "hover",
        children: "children",
        checkStrictly: true,
      },
      // 发送编辑提交分类的请求体
      // catName: "",
      // 编辑分类对话框
      editClassifyVisible: false,
      // 编辑分类的对象
      editClassify: {
        cat_id: "",
        cat_name: "",
        cat_level: 0,
        cat_pid: 0,
      },
      editCascaderProps: {
        label: "cat_name",
        value: "cat_id",
        children: "children",
        checkStrictly: true,
        expandTrigger: "hover",
      },
      // 当前选择的id
      editSelectKeys: [],
      editcascaderlist: [],
      // 改行的父类
      seekData: 0,
    };
  },
  created() {
    this.getClassifylist();
  },
  methods: {
    // 获取分类列表
    async getClassifylist() {
      const { data: res } = await this.$http.get(`categories`, {
        params: this.classifyinfo,
      });
      // console.log(res.data);
      if (res.meta.status !== 200) {
        return this.$message.error(res.meta.msg);
      } else {
        this.classifylist = res.data.result;
        this.total = res.data.total;
        this.$message({
          type: "success",
          message: "获取分类列表成功",
        });
      }
    },
    // 给分类表格表头设置背景颜色
    tableHeaderColor({ row, rowIndex }) {
      if (rowIndex === 0) {
        return "background:#F8F8F9;color:black;";
      }
    },
    // 更改每页行数
    handleSizeChange(newsize) {
      this.classifyinfo.pagesize = newsize;
      this.getClassifylist();
    },
    // 更改页数
    handleCurrentChange(newnum) {
      this.classifyinfo.pagenum = newnum;
      this.getClassifylist();
    },
    // 添加分类
    // 1.获取所有的分类
    addClassifyCascader() {
      axios
        .get(`categories`, { params: { type: 2 } })
        .then(({ data: res }) => {
          // console.log(res, 123);
          this.addcascaderlist = res.data;
          this.addClassifyVisible = true;
        })
        .catch(() => {
          this.$message({
            type: "error",
            message: "获取父级分类失败",
          });
        });
    },
    // 1.首先获取添加用户的请求参数，所选择的值发生变化时打印数组selectKeys的事件
    selectKeysChange(selectKeys) {
      this.$refs.cascaderAddr.dropDownVisible = false;
      if (selectKeys.length > 0) {
        this.addClassify.cat_pid = selectKeys[selectKeys.length - 1];
        this.addClassify.cat_level = selectKeys.length;
      } else {
        this.addClassify.cat_pid = 0;
        this.addClassify.cat_level = 0;
      }
      console.log(selectKeys);
      return;
    },
    // 2.提交添加表单
    submitAddClassify() {
      this.$refs.addClassifyRef.validate((valid) => {
        if (!valid) return;
        axios
          .post(`categories`, this.addClassify)
          .then(({ data: res }) => {
            console.log(res);
            this.$refs.cascaderAddr.dropDownVisible = false;
            this.addClassifyVisible = false;
            this.$message.success("添加分类成功");
            this.getClassifylist();
          })
          .catch(() => {
            this.$message({
              type: "error",
              message: "添加分类失败",
            });
          });
      });
    },
    // 重置添加分类表单
    resetAddClassify() {
      this.selectKeys = 0;
      this.$refs.addClassifyRef.resetFields();
    },
    // 获取该行分类id
    showEditForm(row) {
      axios
        .get(`categories/${row.cat_id}`)
        .then(({ data: res }) => {
          console.log(res);
          this.editClassify = res.data;
          // this.catName = res.data.cat_name;
          this.editClassifyVisible = true;
          var filterpid = this.editClassify.cat_pid;
          // console.log(filterpid, "子级id");
          // 获取所有分类列表
          axios.get("categories").then(({ data: res }) => {
            this.editcascaderlist = res.data;
            this.getEditSelectKeys(this.editcascaderlist, filterpid);
            // console.log(this.seekData,'值');
            if (this.editClassify.cat_level == 0) {
              this.editSelectKeys = this.editClassify.cat_id;
            } else if (this.editClassify.cat_level == 1) {
              this.editSelectKeys = [
                this.editClassify.cat_pid,
                this.editClassify.cat_id,
              ];
            } else {
              // console.log(this.seekData,'第一个数');
              this.editSelectKeys = [
                this.seekData,
                this.editClassify.cat_pid,
                this.editClassify.cat_id,
              ];
            }
            console.log(this.editSelectKeys);
          });
        })
        .catch(() => {
          this.$message({
            type: "error",
            message: "获取该分类id失败",
          });
        });
    },
    // 提交编辑表单
    submitEditClassify() {
      axios
        .put(`categories/${this.editClassify.cat_id}`, this.editClassify
        // {
        //   cat_name: this.editClassify.cat_name,
        // }
        )
        .then(({ data: res }) => {
          this.$refs.cascaderEditr.dropDownVisible = false;
          console.log(res);
          this.editClassifyVisible = false;
          this.getClassifylist();
          this.$message.success("更新表单成功");
        })
        .catch(() => {
          this.$message({
            type: "error",
            message: "更新表单失败",
          });
        });
    },
    // 递归出编辑表单选中的爷级id
    getEditSelectKeys(arr, filterpid) {
      arr.map((item, key) => {
        let findIndex = arr.findIndex((val) => val.cat_id == filterpid);
        if (findIndex !== -1) {
          this.seekData = arr[findIndex].cat_pid;
          // console.log(this.seekData, 123);
        }
        if (findIndex == -1 && item.children) {
          this.getEditSelectKeys(item.children, filterpid);
        }
      });
    },
    // 编辑页更换选中值时，发生的变化
    editSelectKeysChange(newSelectKeys) {
      this.editSelectKeys = newSelectKeys.concat(this.editClassify.cat_id);
      console.log(this.editSelectKeys,2222); 
      this.editClassify.cat_pid = this.editSelectKeys[length-1];
      this.$refs.cascaderEditr.dropDownVisible = false;
      this.getClassifylist();
    },
    // 删除表单
    deleteEditForm(id) {
      this.$confirm("此操作将永久删除该文件, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          axios
            .delete(`categories/${id}`)
            .then(({ data: res }) => {
              console.log(res);
              this.$message.success("删除分类成功");
              this.getClassifylist();
            })
            .catch(() => {
              this.$message({
                type: "error",
                message: "删除分类失败",
              });
            });
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消删除",
          });
        });
    },
  },
};
</script>

<style lang="scss" scoped>
.el-table {
  font-size: 12px;
}
.add_Classify {
  margin-bottom: 15px;
}

.el-cascader {
  width: 100%;
}

.thender {
  .el-radio__inner {
    border: 0px !important;
    background: none;
  }
  .el-radio_input .el-radio_inner {
    background: none;
  }
  .el-radio {
    height: 100%;
    width: 150px;
    opacity: 0;
    position: absolute;
    z-index: 10;
    visibility: hidden; // 加上这一行
  }
}
</style>